package com.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class FileUploadController {
    // 得到一个用来记录日志的对象，这样在打印信息时能够标记打印的是哪个类的信息

    @RequestMapping("/getmultiFile")
    public String getmultiFile() {
        return "multiFiles";
    }

    @RequestMapping("/getFileUpload")
    public String getFileUpload() {
        return "fileUpload";
    }
    /**
     * 单文件上传
     */
    @RequestMapping("/fileupload")
    public String oneFileUpload(MultipartFile myfile,String description, Model model) throws IOException {
        //上传到nginx目录 通过nginx查看文件 或者访问文件
        String realpath = "c:/aServer";
        String fileName = myfile.getOriginalFilename();
        File targetFile = new File(realpath, fileName);

        if (!targetFile.exists()) {//如果上面的realpath不存在 则创建
            targetFile.mkdirs();
        }

        // 上传
        myfile.transferTo(targetFile);

        model.addAttribute("fileName",fileName);
        model.addAttribute("description",description);

        return "showFile";
    }


    /**
     * 多文件上传
     */
    @RequestMapping("/multifile")
    public String multiFileUpload(List<MultipartFile> myfile, Model model) throws IOException {
        String realpath = "c:/aServer";
        File targetDir = new File(realpath);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        List<String> files = new ArrayList<>();
        System.out.println("files"+myfile);
        for (int i = 0; i < myfile.size(); i++) {
            MultipartFile file = myfile.get(i);
            String fileName = file.getOriginalFilename();
            File targetFile = new File(realpath, fileName);
            // 上传
            file.transferTo(targetFile);
            files.add(fileName);
        }

        model.addAttribute("files",files);

        return "showMulti";
    }

}
